Best Practices for Configuring Azure App Insights to Monitor .NET Core Apps

您所在的位置:网站首页 life insight app Best Practices for Configuring Azure App Insights to Monitor .NET Core Apps

Best Practices for Configuring Azure App Insights to Monitor .NET Core Apps

2024-07-05 02:41| 来源: 网络整理| 查看: 265

Best Practices for Configuring Azure App Insights to Monitor .NET Core AppsSusitha Bandara

Susitha Bandara

·

Follow

8 min read·Apr 7, 2023

--

Azure App Insights is a powerful tool for monitoring the performance and usage of your .NET Core applications in the cloud. With App Insights, you can gain real-time insights into your app’s performance, diagnose issues quickly, and optimize your app for better performance.

In this article, we’ll look at some best practices for configuring Azure App Insights to monitor your .NET Core apps. We’ll cover everything from setting up App Insights to tracking custom telemetry data and using the App Insights API.

Getting Started with Azure App Insights

To get started with Azure App Insights, you’ll need an Azure subscription and a .NET Core app running in Azure. Once you have these set up, you can configure App Insights by following these steps:

Create an App Insights resource in the Azure portal.Add the Microsoft.ApplicationInsights.AspNetCore NuGet package to your .NET Core app.Update your app’s Startup.cs file to add App Insights middleware to your app’s request pipeline.Configure App Insights to monitor your app’s performance, availability, and usage.

Let’s take a closer look at each of these steps.

1. Create an App Insights Resource

To create an App Insights resource in the Azure portal, follow these steps:

Go to the Azure portal and log in to your Azure account.Click the “+ Create a resource” button in the left-hand menu.Search for “App Insights” in the search box and select “Application Insights” from the search results.Click the “Create” button.Enter a name and choose a subscription, resource group, and location for your App Insights resource.Click the “Review + create” button, then click the “Create” button to create your App Insights resource.2. Add the Microsoft.ApplicationInsights.AspNetCore NuGet Package

To add the Microsoft.ApplicationInsights.AspNetCore NuGet package to your .NET Core app, follow these steps:

Open your app’s solution in Visual Studio.Right-click on your app’s project in the Solution Explorer and select “Manage NuGet Packages”.Search for “Microsoft.ApplicationInsights.AspNetCore” in the search box.Click the “Install” button to install the package.3. Update your app’s Startup.cs file

To add App Insights middleware to your app’s request pipeline, add the following code to your app’s Startup.cs file:

public void Configure(IApplicationBuilder app, IHostingEnvironment env){ // Add App Insights middleware to the request pipeline app.UseApplicationInsightsRequestTelemetry();

if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); }

app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy();

// Add App Insights middleware to the request pipeline app.UseApplicationInsightsExceptionTelemetry();

app.UseMvc();}

4. Configure App Insights to Monitor Your App’s Performance, Availability, and Usage

Once you’ve set up App Insights in your app, you can configure it to monitor your app’s performance, availability, and usage. Here are some best practices for doing so:

Enable Server-Side Telemetry

Server-side telemetry is essential for monitoring your app’s performance and usage. To enable server-side telemetry, add the following code to your app’s Startup.cs file:

services.AddApplicationInsightsTelemetry();

This code registers the App Insights telemetry services with the .NET Core dependency injection system.

Configure Performance Monitoring

To monitor the performance of your .NET Core app using App Insights, you can configure the following:

Request Monitoring: Monitor the performance of each HTTP request made to your app, including response time, request count, and error rate. To enable request monitoring, add the following code to your app’s Startup.cs file:services.AddApplicationInsightsTelemetry(options =>{ options.EnableRequestTrackingTelemetryModule = true;});Dependency Monitoring: Monitor the performance of external dependencies used by your app, such as databases, APIs, and external services. To enable dependency monitoring, add the following code to your app’s Startup.cs file:services.AddApplicationInsightsTelemetry(options =>{ options.EnableDependencyTrackingTelemetryModule = true;});Configure Availability Monitoring

App Insights can also monitor the availability of your .NET Core app by sending pings to your app’s endpoints and tracking their response status codes. To enable availability monitoring, add the following code to your app’s Startup.cs file:

services.AddApplicationInsightsTelemetry(options =>{ options.AddAutoDependencyCorrelation = true; options.EnableAvailabilityTracking = true;});

This code configures App Insights to send availability pings to your app’s endpoints and track their response status codes.

Track Custom Telemetry Data

App Insights allows you to track custom telemetry data in addition to the default telemetry data it collects. This can be useful for tracking business-specific metrics or logging custom events. To track custom telemetry data, you can use the following code:

var telemetry = new TelemetryClient();telemetry.TrackEvent("MyCustomEvent");telemetry.TrackMetric("MyCustomMetric", 123);

This code logs a custom event and a custom metric to App Insights. You can view this data in the App Insights portal.

Use the App Insights API

Finally, you can use the App Insights API to retrieve telemetry data programmatically. This can be useful for creating custom dashboards or integrating App Insights data with other tools. To use the App Insights API, you can use the following code:

var client = new TelemetryClient();var query = client.CreateQuery("requests | summarize count()");var result = query.Execute();

This code retrieves the count of all HTTP requests made to your app and stores it in the result variable.

Following is an complete example code written in C# .NET Core with App Insights configuration:

using Microsoft.ApplicationInsights;using Microsoft.ApplicationInsights.Extensibility;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;

namespace MyApp{ public class Startup { public IConfiguration Configuration { get; }

public Startup(IConfiguration configuration) { Configuration = configuration; }

public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews();

// Add App Insights telemetry services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"]);

// Configure App Insights request monitoring services.ConfigureTelemetryModule( (module, options) => { module.CollectionOptions.InjectResponseHeaders = true; });

// Configure App Insights dependency monitoring services.ConfigureTelemetryModule( (module, options) => { module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.ServiceBus"); }); }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); }

app.UseStaticFiles();

app.UseRouting();

app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } }}

In this example code, we configure App Insights telemetry for our .NET Core app by calling services.AddApplicationInsightsTelemetry() and passing in our App Insights instrumentation key as a configuration value.

We also configure request monitoring by calling services.ConfigureTelemetryModule(), which enables tracking of HTTP request telemetry, and services.ConfigureTelemetryModule(), which enables tracking of external dependency telemetry.

Finally, we configure our app’s middleware pipeline using the app.Use*() methods provided by the Microsoft.AspNetCore.Builder namespace.

By following this example, you can configure your .NET Core app to use App Insights and gain valuable insights into its performance, availability, and usage.

How we can identify, diagnose and fix a bug in application using App insight telemetry?

Now let’s discuss how to identify a bug in the application that we monitor using App Insights and how to find the line of code where this bug occurs.

First, we need to configure App Insights to track the relevant telemetry. This includes setting up logging, exception tracking, and custom events that are specific to our application. Once App Insights is properly configured, it will automatically start collecting telemetry data, such as request data, dependency data, and exceptions.

To identify a bug in our application, we can use the following steps:

Identify the issue: When a user reports an issue, we can start by searching for relevant logs and exceptions in App Insights. For example, if a user reports that they are unable to complete a checkout process, we can look for exceptions related to the checkout process, or we can look for slow or failed requests related to the checkout process.Use the search feature: App Insights provides a powerful search feature that allows us to search for specific telemetry data using a rich query language. For example, we can use the following query to search for exceptions related to the checkout process:exceptions| where operation_Name == "Checkout"

This query will return a list of exceptions that occurred during the checkout process, along with information such as the exception message, stack trace, and correlation ID.

3. Analyze the telemetry data: Once we have identified the relevant telemetry data, we can analyze it to find the root cause of the issue. For example, we can look at the exception message and stack trace to determine which part of the code is causing the exception.

4. Use the Application Map: App Insights also provides an Application Map feature that can help us visualize the dependencies between different components of our application. This can help us identify issues that are caused by external dependencies, such as a slow or failing API.

5. Debug the code: Once we have identified the line of code where the issue is occurring, we can use a debugger to step through the code and determine the root cause of the issue. We can also use the logging features of App Insights to log additional information, such as variable values, to help us debug the issue.

Here is an example of how we can use App Insights to find the line of code where an exception is occurring:

Suppose we have a .NET Core web application that is throwing an exception when a user tries to submit a form. We can use the following steps to find the line of code where the exception is occurring:

Identify the issue: A user reports that they are unable to submit a form and are seeing an error message.Use the search feature: We can use the following query to search for exceptions related to form submissions:exceptions| where operation_Name == "SubmitForm"

This query will return a list of exceptions that occurred during form submissions, along with information such as the exception message, stack trace, and correlation ID.

3. This query will return a list of exceptions that occurred during form submissions, along with information such as the exception message, stack trace, and correlation ID.

4. Analyze the telemetry data: We can look at the exception message and stack trace to determine which part of the code is causing the exception. For example, the exception message might indicate that a null reference exception occurred when trying to access a particular object.

5. Use the Application Map: We can use the Application Map feature to visualize the dependencies between different components of our application. For example, we might see that the form submission process relies on an external API that is currently experiencing issues.

6. Debug the code: Once we have identified the line of code where the exception is occurring, we can use a debugger to step through the code and determine the root cause of the issue. We can also use the logging features of App Insights to log additional information, such as variable values, to help us debug the issue. Here is an example of how we can configure logging in our .NET Core application to log additional information when an exception occurs:

using Microsoft.ApplicationInsights;using Microsoft.ApplicationInsights.AspNetCore;using Microsoft.Extensions.Logging;

public class Startup{ public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { // Configure App Insights TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault(); configuration.InstrumentationKey = ""; app.UseApplicationInsightsRequestTelemetry(configuration); app.UseApplicationInsightsExceptionTelemetry(configuration);

// Configure logging ILogger logger = loggerFactory.CreateLogger("CustomLogger");

app.Use(async (context, next) => { try { await next(); } catch (Exception ex) { logger.LogError(ex, "An error occurred"); throw; } });

// ... }}

In this example, we are configuring App Insights to track request telemetry and exception telemetry, and we are also configuring a custom logger using ILoggerFactory. We then use the app.Use middleware to catch any exceptions that occur and log them using our custom logger.

By using these techniques, we can quickly identify and debug issues in our .NET Core application using App Insights.

Conclusion

In this article, we’ve covered some best practices for configuring Azure App Insights to monitor your .NET Core apps. By following these best practices, you can gain valuable insights into your app’s performance, availability, and usage, and diagnose issues quickly. Whether you’re a junior developer just getting started with Azure, or an experienced developer looking to optimize your app’s performance, App Insights is a powerful tool that can help you achieve your goals.



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3